谈谈 Redux
是什么
React-Redux 目的是为了关联 React 和 Redux,核心 api 是 Provider 和 connect。
ReactRedux 的核心概念
connect(mapStateToProps,mapDispatchToProps)(Component):connect 是高阶组件,把组件和 store 连接起来,产生一个新的组件
mapStateToProps : reducer 中 state
mapDispatchToProps: action 中 方法
示例
actionTypes.js
常量
export const INCREMENT = "INCREMENT";
export const DECREASE = "DECREASE";
actions.js
方法
import { INCREMENT, DECREASE } from "./actionTypes";
export function incrementAction() {
return {
type: INCREMENT
};
}
export function decreaseAction() {
return {
type: DECREASE
};
}
reducer.js
计算
const initialState = {
value: 0
};
function addReducer(state = initialState, action) {
switch (action.type) {
case "INCREMENT":
return { ...state, value: state.value + 1 };
case "DECREASE":
return { ...state, value: state.value - 1 };
default:
return state;
}
}
export default addReducer;
store.js
中心管理
import { createStore } from "redux";
import reducers from "./reducer";
const store = createStore(reducers);
export default store;
App.js
父级 通过 Provider 包裹 子组件,传递 store 对象
import React from "react";
import Page from "./Page";
import store from "./store";
import { Provider } from "react-redux";
const App = () => (
<Provider store={store}>
<Page />
</Provider>
);
export default App;
Page.js
connect 传递 state 和 action 给子组件
connect 返回一个有 prop 的新组件,新组件通过 props,拿到 state 也可以 dispatch 派发动作
import React, { PureComponent } from "react";
import { connect } from "react-redux";
import { incrementAction, decreaseAction } from "./actions";
class Page extends PureComponent {
render() {
const { value, incrementAction, decreaseAction } = this.props;
return (
<div>
<h1>{value}</h1>
<button onClick={incrementAction}>increment</button>
<button onClick={decreaseAction}>decrease</button>
</div>
);
}
}
const mapStateToProps = (state) => ({
value: state.value
});
const mapDispatchToProps = (dispatch) => ({
incrementAction: () => dispatch(incrementAction()),
decreaseAction: () => dispatch(decreaseAction())
});
export default connect(mapStateToProps, mapDispatchToProps)(Page);